package org.dromara.neutrinoproxy.client.mini;

import org.dromara.neutrinoproxy.client.core.ProxyClientService;
import org.dromara.neutrinoproxy.client.event.*;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.bean.InitializingBean;

public class DesktopService implements IEventCallback {

    private ProxyClientService proxyClientService;

    /**
     * 窗口
     */
    private MyWindow window;

    /**
     * 任务栏图标
     */
    private MyTrayIcon trayIcon;


    /**
     * 初始化任务栏图标
     */
    public void start() {
        // 启动图标
        window = new MyWindow();
        trayIcon = new MyTrayIcon(window);
        trayIcon.showTray();
    }

    private static DesktopService desktopService;
    public static DesktopService getInstance() {
        if(desktopService == null){
            desktopService = new DesktopService();
        }
        return desktopService;
    }


    /**
     * 传递proxyClientService 并且 更新状态
     * @param proxyClientService
     */
    public void updateService(ProxyClientService proxyClientService) {
        this.proxyClientService = proxyClientService;
        window.setProxyClientService(proxyClientService);

        updateEvent();
        updateData();
    }

    /**
     * 初始化状态、数据、及回调事件
     */
    private void updateEvent() {
        EventContainer.getInstance().subscribe(this);
    }


    /**
     * 初始化状态、数据、及回调事件
     */
    private void updateData(){
        String currentLicenseKey = this.proxyClientService.getCurrentLicenseKey();
        ClientDataService.getInstance().setLicenseKey(currentLicenseKey);
        ClientDataService.getInstance().setConnected(this.proxyClientService.connected());
        ClientDataService.getInstance().setConnecting(this.proxyClientService.isConnecting());
        ClientDataService.getInstance().notifyDataChanged();
    }

    @Override
    public void onReceive(BaseEvent event) {
        if(event instanceof ConnectingEvent){
            ClientDataService.getInstance().setConnecting(((ConnectingEvent)event).isConnecting());
        } else if(event instanceof ConnectedEvent){
            ClientDataService.getInstance().setConnected(((ConnectedEvent)event).isConnected());
        } else if(event instanceof LicenseKeyChangedEvent){
            ClientDataService.getInstance().setLicenseKey(((LicenseKeyChangedEvent)event).getLicenseKey());
        }
        ClientDataService.getInstance().notifyDataChanged();

    }
}
